<?php

namespace App\Http\Controllers;
use Config;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ArticleRequest;

class ArticleController extends Controller
{
   /*
    文章添加表单
    /admin/article/add
   */
	public static function getAdd(){

    	$data = self::getSelect();
    	return view('/article/add',['list'=>$data]);
	}

	public static function getSelect(){
		 //查询文章类别 
    	// $data = DB::table('cates')->get();

    	$data = DB::select('select *,concat(path,",",id) as paths from cates_is order by paths');
    	//处理分页
    	foreach($data as $k=>$v){
    		// echo '|----'.$v['name'].'<br>';
    		$len = explode(',',$v['path']);
    		$num = count($len)-1;
    		// echo $num.'|--'.$v['name'].'<br>';
    		$data[$k]['name'] = str_repeat('|---',$num).$v['name'];
    	}
    	return $data;
	}
	/*
		执行数据添加
		/admin/article/inster
	*/						//做验证的类
							//app/Http/Request/ArticleRequest
	public function postInster(ArticleRequest $request){
			//做验证
		/*
			1.使用php artisan make:request ArticleRequest 创建请求对象
				APP\Http\Request 查找新建的请求对象
			2.在请求对象代码中的authorize方法中
				return true;
			3.如何使用请求对象
				控制器方法的类约束需要执行请求对象的类名
			4.需要导入请求对象
				use App\Http\Requests\ArticleRequest;


		*/
			// dd($request->all());
		//2.处理数据
		$data = self::Deal($request);
		//执行插入数据
		$res = DB::table('articles')->insert($data);
		if($res){
			return redirect('/admin/article/index')->with('success','添加成功');
		}else{
			return back()->with('error','添加失败');
		}
	}


	/*
		文章列表显示
		/admin/article/index
	
	*/
	public function getIndex(Request $request){
		//数据填充 插入测试数据
		/*
			1.创建数据填充类 
				php artisan make:seeder ArticleSeeder
				在\database\seeds目录下查找新建的填充类
			2.在ArticleSeeder类的run方法中编写插入代码
				 //数据填充
		        $data = [];
		        for($i=0;$i<100;$i++){
		        	$temp['title']=str_random(20);
		        	$temp['content']=str_random(30);
		        	$temp['descr']=str_random(30);
		        	$temp['user_id']=rand(1,10);
		        	$temp['cate_id']=rand(1,4);
		        	$temp['pic']=str_random(20);
		        	$temp['create_t']=date('Y-m-d H:i:s');
		        	$data[]=$temp;
		        }
		        \DB::table('articles')->insert($data);
		    }
		   3.使用 php artisan 命令执行run方法实现数据填充
		   	php artisan db:seed --class = ArticleSeeder

		*/
		// dd($request->all());
		//查询文章的数据
		$data = DB::table('articles')->where(function($query) use($request){
				if($request->has('keywords')){
					$query->where('title','like','%'.$request->input('keywords').'%');
				}
		})->paginate($request->input('num',5));
		return view('article.index',['list'=>$data,'request'=>$request->all()]);
	}

	/*
		执行修改
		/admin/article/edit/{id}
	
	*/

	public function getEdit($id){
		//查询类别数据
		$cate = self::getSelect();
		//查询该条数据
		$data = DB::table('articles')->where('id','=',$id)->first();

		return view('article.edit',['vo'=>$data,'list'=>$cate]);
	}

	/*
		处理数据
	*/
		public static  function Deal(Request $request){
			//判断是否有图片上传
		$res = $request->hasFile('pic');
		if($res){
			//获取随机图片名和后缀
			$picpath = time().rand(1000,9999).'.'.$request->file('pic')->getClientOriginalExtension();
			//有图片上传  php必须使用图片的相对路径(index.php同级目录)绝对路径 指D:盘符
			$request -> file('pic')->move(Config::get('app.upload_dir'),$picpath);
			//封装图片的上传数据  路径存储的时候必须使用绝对路径
			$data['pic'] = trim(Config::get('app.upload_dir').$picpath,'.');
		}
			//标题
		$data['title'] = $request->input('title');
			//内容
		$data['content'] = $request->input('editorValue');
			//描述
		$data['descr'] = $request->input('descr');
			//用户ID	
		$data['user_id'] = 1;
			//那个类下面的id
		$data['cate_id'] = $request->input('cate_id');
			//时间戳
		$data['create_t'] = time();

		return $data;
		// dd($data);
		} 
	/*
		执行修改
		/admin/article/update
	
	*/
	public function postUpdate(ArticleRequest $request){
		//验证数据

		//处理数据
		$data = self::Deal($request);
		//执行修改
		 // dd($data);
		 $res = DB::table('articles')->where('id','=',$request->input('id'))->update($data);
		 // dd($res);
		if($res){
			return redirect('/admin/article/index')->with('success','修改成功');
		}else{
			return back()->with('error','修改失败');
		}
	}

	/*
		执行删除
		/admin/article/del/{id}

	*/

	public function getDel($id){
		//执行删除
		//查询该条数据获取图片的路径
		$data = DB::table('articles')->where('id','=',$id)->first();

		// 1.删除主图
		if(file_exists('.'.$data['pic'])){
			unlink('.'.$data['pic']);
		}
		
		//2.删除详情中的图片
		$str = $data['content'];
		preg_match_all('/src=[\'\"]([^\'\"]*)[\'\"]/i',$str,$temp);
		foreach($temp[1] as $v){
			if(file_exists('.'.$v)){
				unlink('.'.$v);
			}
		}
		//3.删除数据
		$res = DB::table('articles')->where('id','=',$id)->delete();
		if($res){
			return redirect('/admin/article/index')->with('success','删除成功');
		}else{
			return back()->with('error','删除失败');
		}
	}
 
}
